from datetime import datetime

from flask import Blueprint, request, redirect, url_for, jsonify, render_template, session
from sqlalchemy import or_, and_
from werkzeug.security import generate_password_hash
import pymysql
from models import BookModel
from models import UserModel
from models import tb_user_borrow
from exts import db
import math

global borrowlist
global users

admin = Blueprint("admin", __name__, url_prefix="/admin")


@admin.route("/borrow")
def borrow():
    global borrowlist
    session['borrow_search'] = ""
    result = db.session.query(tb_user_borrow).filter().all()
    print(result)
    borrowlist = list(result)
    print(borrowlist)
    session['borrowsum'] = len(borrowlist)
    session['borrowpages'] = math.ceil(session['borrowsum'] / 10)
    blist = borrowlist[:10]
    return render_template("admin-borrow-manage.html", nowpage=1, borrowlist=blist, now=datetime.now())


@admin.route("borrow/<page>", methods=['POST'])
def borrow_turn(page):
    page = int(page)
    mmax = min(session['borrowsum'], (page * 10))
    global borrowlist
    blist = borrowlist[(page - 1) * 10:mmax]
    return render_template("admin-borrow-manage.html", nowpage=page, borrowlist=blist, now=datetime.now())


@admin.route("/borrow/jump", methods=['POST'])
def borrow_jump():
    page = request.values.get('page')
    return borrow_turn(page)


@admin.route("/user", methods=['GET'])
def usr():
    session['search_username'] = ""
    global users
    users = UserModel.query.filter(and_(UserModel.permissions.in_([1, 2, 3]), UserModel.isdeleted.in_([1])))
    users = list(users)
    session['usersnum'] = len(users)
    session['userspages'] = math.ceil(session['usersnum'] / 10)
    user = users[:10]
    return render_template("admin-user-manage.html", nowpage=1, user=user)


@admin.route("/user/<page>", methods=["GET"])
def turn_page(page):
    page = int(page)
    mmax = min(session['usersnum'], (page*10))
    global users
    user = users[(page-1)*10:mmax]
    return render_template("admin-user-manage.html", nowpage=page, user=user)


@admin.route("/user/turn", methods=['POST'])
def jump_page():
    page = request.values.get('page')
    return turn_page(page)


@admin.route("/center")
def center():
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    return render_template("admin-self-center.html", usr=user)


@admin.route("/search", methods=['POST'])
def search():
    global users
    name = request.values.get("name")
    session['search_username'] = name
    users = UserModel.query.filter(or_(UserModel.school.contains(name), UserModel.username.contains(name), UserModel.nickname.contains(name)))
    users = list(users)
    session['usersnum'] = len(users)
    session['userspages'] = math.ceil(session['usersnum'] / 10)
    user = users[:10]
    return render_template("admin-user-manage.html", nowpage=1, user=user)


@admin.route("/update", methods=['POST'])
def update():
    username = request.values.get("username")
    nickname = request.values.get("nickname")
    phone = request.values.get("phonenum")
    school = request.values.get("school")
    power = request.values.get("power")
    if power == "普通用户":
        power = 1
    else:
        power = 2
    user = UserModel.query.filter_by(username=username).first()
    user.nickname = nickname
    user.phone = phone
    user.school = school
    user.permissions = power
    db.session.commit()
    return usr()


@admin.route("/ban", methods=['POST'])
def ban():
    name = request.values.get("username")
    user = UserModel.query.filter_by(username=name).first()
    user.permissions = 3
    db.session.commit()
    return usr()


@admin.route("/add_user", methods=['POST'])
def useradd():
    username = request.values.get("uusername")
    password = request.values.get("ppassword")
    phone = request.values.get("pphonenum")
    school = request.values.get("sschool")
    print(username)
    print(password)
    print(phone)
    print(school)
    userss = UserModel.query.filter_by(username=username)
    if userss.count() > 0:
        return jsonify({'status': '0', 'errmsg': 'fail'})
    user = UserModel(username=username, password=generate_password_hash(password), phone=phone, school=school)
    user.nickname = username + "-sztu"
    db.session.add(user)
    db.session.commit()
    return usr()


@admin.route("/search_borrow", methods=['POST'])
def search_borrow():
    name = request.values.get('usrname')
    session['borrow_search'] = name
    global borrowlist
    result = db.session.query(tb_user_borrow).filter().all()
    borrow = list(result)
    borrowlist = []
    for x in borrow:
        if name in x.user_name:
            borrowlist.append(x)
    session['borrowsum'] = len(borrowlist)
    session['borrowpages'] = math.ceil(session['borrowsum'] / 10)
    blist = borrowlist[:10]
    return render_template("admin-borrow-manage.html", nowpage=1, borrowlist=blist, now=datetime.now())




